package main

import (
	"flag"
	"fmt"
	"net"
	"time"
)

var addr = flag.String("a", "localhost:1833", "address")
var num = flag.Int("c", 1, "connection number")
var timeOut = flag.Int("t", 20, "timeout second")
var msgLen = flag.Int("m", 1024, "message length")

var msg []byte

func main() {
	flag.Parse()

	fmt.Printf("*** %d connections, %d seconds, %d byte packets ***\n", *num, *timeOut, *msgLen)

	// msg = make([]byte, *msgLen)
	// rand.Read(msg)

	startC := make(chan interface{})
	closeC := make(chan interface{})
	result := make(chan int64, *num)
	req := make(chan int64, *num)

	for i := 0; i < *num; i++ {
		conn, err := net.Dial("tcp", *addr)
		if err != nil {
			panic(err)
		}
		go handler(conn, startC, closeC, result, req)
	}
	fmt.Println("??")
	// start
	close(startC)
	fmt.Println("===!!")

	time.Sleep(time.Duration(*timeOut) * time.Second)
	fmt.Println("!!")

	// stop
	close(closeC)

	var totalMessagesRead, reqCount int64
	for i := 0; i < *num; i++ {
		totalMessagesRead += <-result
		reqCount += <-req
	}

	fmt.Println(totalMessagesRead/int64(*timeOut*1024*1024), " MiB/s throughput")
	fmt.Println(reqCount/int64(*timeOut), " qps")
}

func handler(conn net.Conn, startC chan interface{},
	closeC chan interface{}, result, req chan int64) {
	<-startC

	// _, e := conn.Write(msg)
	// if e != nil {
	// 	fmt.Println("Error to send message because of ", e.Error())
	// }

	var packet [0xFFF]byte
	for {
		_, _ = conn.Write([]byte("abcd"))

		n, err := conn.Read(packet[:])
		if err != nil {
			fmt.Println("Read error  ", err.Error())

			return
		}
		fmt.Println("packet[:n]", string(packet[:n]))
		_, _ = conn.Write(packet[:n])
	}

	// // buf := make([]byte, 32)
	// for {
	// 	select {
	// 	case <-closeC:
	// 		result <- count
	// 		req <- reqCount
	// 		fmt.Println("reqCount", reqCount)
	// 		conn.Close()
	// 		return
	// 	default:

	// 		// time.Sleep(200 * time.Millisecond)
	// 	}
	// }

}
